package com.zcs.app.lucky.data

import cn.sxw.android.base.utils.MMKVUtils
import com.alibaba.fastjson.JSON
import com.zcs.app.lucky.entity.LuckyEntity
import com.zcs.app.lucky.isJsonList

/**
 * 抽奖数据缓存
 */
object LuckyDataCache {
    private const val KEY_LUCKY_LIST = "KEY_LUCKY_LIST"

    private lateinit var list: ArrayList<LuckyEntity>

    fun loadAll(): ArrayList<LuckyEntity> {
        val json = MMKVUtils.getString(KEY_LUCKY_LIST)
        list = if (json.isJsonList()) {
            JSON.parseArray(json, LuckyEntity::class.java) as ArrayList<LuckyEntity>
        } else {
            ArrayList()
        }
        return list
    }

    fun update(entity: LuckyEntity) {
        add(entity, isModify = true)
    }

    fun add(entity: LuckyEntity, isModify: Boolean = false) {
        // 1.如果是修改，先移除上一个
        if (isModify) {
            removeById(entity.id)
        }
        // 在首部添加
        list.add(0, entity)
        notifyOnChanged()
    }

    private fun notifyOnChanged() {
        MMKVUtils.put(KEY_LUCKY_LIST, JSON.toJSONString(list))
    }

    fun findByIdOrNewInstance(id: String): LuckyEntity {
        for (item in list) {
            if (item.id == id) {
                return item
            }
        }
        return LuckyEntity()
    }

    fun findByIdOnNull(id: String): LuckyEntity? {
        for (item in list) {
            if (item.id == id) {
                return item
            }
        }
        return null
    }

    fun removeById(id: String, notify: Boolean = false) {
        for (item in list) {
            if (item.id == id) {
                list.remove(item)
                break
            }
        }
        if (notify) notifyOnChanged()
    }
}
